package com.peking.donations.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.peking.donations.base.util.StringUtils;
import com.peking.donations.constants.ACTCacheNames;
import com.peking.donations.dao.DonationUserDao;
import com.peking.donations.model.DonationUser;
import com.peking.donations.service.UserService;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by wyz on 16/4/27.
 */
@Service("userService")
@Transactional(readOnly =  true)
public class UserServiceImpl implements UserService {

    private org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private DonationUserDao userDao;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    @Transactional(readOnly = false)
    public DonationUser saveUser(DonationUser user) {

        DonationUser donationUser = userDao.save(user);

        redisTemplate.opsForHash().increment(ACTCacheNames.ACT_GlOAB_STATISTIC.name(), "joins", 1);

        redisTemplate.opsForHash().put(ACTCacheNames.ACT_DONAION_USER.name(),donationUser.getId()+"", JSONObject.toJSONString(donationUser));
        return donationUser;
    }

    @Override
    @Transactional(readOnly = false)
    public DonationUser updateUser(DonationUser user) {
        user = userDao.save(user);
        redisTemplate.opsForHash().put(ACTCacheNames.ACT_DONAION_USER.name(),user.getId()+"", JSONObject.toJSONString(user));
        return user;
    }

    @Override
    public DonationUser findByOpenId(String openId) {
        return userDao.findByWeixinOpenId(openId);
    }

    @Override
    @Transactional(readOnly = false)
    public DonationUser updateUser(int userId,String grade, String department,String code) {
        DonationUser object = userDao.findOne(userId);
        object.setGrade(grade);
        object.setDepartment(department.trim());
        object.setDepartmentCode((code==null||code =="")?"-1":code);
        object = userDao.save(object);
        redisTemplate.opsForHash().put(ACTCacheNames.ACT_DONAION_USER.name(),object.getId()+"", JSONObject.toJSONString(object));
        redisTemplate.opsForHash().increment(ACTCacheNames.ACT_GRADE_ORDER.name(), object.getGrade() + "_" + object.getDepartmentCode().trim(), 1);
        String order = (String) redisTemplate.opsForHash().get(ACTCacheNames.ACT_GRADE_ORDER.name(), object.getGrade() + "_" + object.getDepartmentCode().trim());
        redisTemplate.opsForHash().put(ACTCacheNames.ACT_GRADE_ORDER.name(), object.getGrade() + "_" + object.getDepartmentCode()+"_userId",order);
        return object;
    }

    @Override
    public DonationUser findById(int userId) {
        return userDao.findOne(userId);
    }
}
